<?php

namespace app\adminapi\logic\room\department;

use app\common\enum\DefaultEnum;
use app\common\enum\InitEnum;
use app\common\model\room\department\RoomDepartment;
use app\common\model\room\department\RoomDepartmentDevice;
use app\common\model\room\department\RoomDepartmentDeviceLog;
use app\common\logic\BaseLogic;
use app\common\model\room\RoomDepartmentLog;
use think\facade\Db;


/**
 * 科室设备逻辑
 * Class RoomDepartmentDeviceLogic
 * @package app\adminapi\logic\room
 */
class RoomDepartmentDeviceLogic extends BaseLogic {


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/23 10:30
     */
    public static function add(array $params): bool {
        Db::startTrans();
        try {
            if ($params['device'][0] != $params['department'][0]) {
                self::setError('设备信息和科室信息需在同一个院区');
                return false;
            }
            $insert_data = [
                'bid' => $params['department'][1],
                'department_id' => $params['department'][2],
                'status' => $params['status'] ?? DefaultEnum::SHOW,
                'sort' => $params['sort'] ?? 1,
                'device_id' => $params['device'][1] ?? 0,
                'department' => json_encode($params['department']),
                'device' => json_encode($params['device']),
                'coefficient' => $params['coefficient'] ?? 1,
                'price' => $params['price'] ?? 0,
                'reading' => $params['reading'] ?? 0,
                'base_number' => $params['base_number'] ?? 0,
                'log_time' => date('Y-m-d H:i:s', time()),
                'lift_fee' => $params['coefficient'] ?? 0,
                'second_pressure_fee' => $params['second_pressure_fee'] ?? 0,
                'is_init' => InitEnum::NO,
            ];
            //计价电量
            $insert_data['use_total'] = bcsub($insert_data['reading'], $insert_data['base_number'], 4);
            $insert_data['total_fee'] = bcsub($insert_data['reading'], $insert_data['base_number'], 4) * $insert_data['price'] * $insert_data['coefficient'];
            $device = RoomDepartmentDevice::create($insert_data);
            //添加记录
            $log_data = [
                'cid' => $params['department'][0],
                'device_id' => $insert_data['device_id'],
                'room_device_id' => $device->id,
                'coefficient' => $insert_data['coefficient'],
                'price' => $insert_data['price'],
                'base_number' => $insert_data['base_number'],
                'reading' => $insert_data['reading'],
                'use_total' => $insert_data['use_total'],
                'lift_fee' => $insert_data['lift_fee'],
                'second_pressure_fee' => $insert_data['second_pressure_fee'],
                'total_fee' => $insert_data['total_fee'],
                'log_time' => $insert_data['log_time'],
            ];
            RoomDepartmentDeviceLog::create($log_data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/23 10:30
     */
    public static function edit(array $params): bool {
        $info = RoomDepartmentDevice::find($params['id']);
        Db::startTrans();
        try {
//            if ($params['device'][0] != $params['department'][0]) {
//                self::setError('设备信息和科室信息需在同一个院区');
//                return false;
//            }
            $insert_data = [
//                'bid'                           => $params['department'][1],
//                'department_id'                 => $params['department'][2],
                'status' => $params['status'] ?? DefaultEnum::SHOW,
//                'sort'                          => $params['sort'] ?? 1,
//                'device_id'                     => $params['device'][1] ?? 0,

                'device_name' => $params['device_name'],
                'device_no' => $params['device_no'],
                'device_type' => $params['device_type'],

                'department' => json_encode($params['department']),
                'device' => json_encode($params['device']),
                'coefficient' => $params['coefficient'] ?? 1,
                'price' => $params['price'] ?? 0,
                'reading' => $params['reading'] ?? 0,
                'base_number' => $params['base_number'] ?? 0,
                'log_time' => date('Y-m-d H:i:s', time()),
                'lift_fee' => $params['coefficient'] ?? 1,
                'second_pressure_fee' => $params['second_pressure_fee'] ?? 0,
            ];

            //计价电量
            $insert_data['use_total'] = bcsub($insert_data['reading'], $insert_data['base_number'], 4);
            $insert_data['total_fee'] = bcsub($insert_data['reading'], $insert_data['base_number'], 4) * $insert_data['price'] * $insert_data['coefficient'];
            RoomDepartmentDevice::where('id', $params['id'])->update($insert_data);

//            //未初始化
//            if ($info['is_init'] == InitEnum::NO) {
//                //获取最新的
//                $last_log = RoomDepartmentDeviceLog::where('device_id', $params['id'])->order('create_time', 'desc')->find();
//                $log_data   = [
//                    'cid'                   => $params['department'][0],
//                    'device_id'             => $insert_data['device_id'],
//                    'room_device_id'        => $params['id'],
//                    'coefficient'           => $insert_data['coefficient'],
//                    'price'                 => $insert_data['price'],
//                    'base_number'           => $insert_data['base_number'],
//                    'reading'               => $insert_data['reading'],
//                    'use_total'             => $insert_data['use_total'],
//                    'lift_fee'              => $insert_data['lift_fee'],
//                    'second_pressure_fee'   => $insert_data['second_pressure_fee'],
//                    'total_fee'             => $insert_data['total_fee'],
//                    'log_time'              => $insert_data['log_time'],
//                ];
//                RoomDepartmentDeviceLog::where('id',$last_log['id'])->update($log_data);
//            } else {
//                //添加记录
//                $log_data   = [
//                    'cid'                   => $params['department'][0],
//                    'device_id'             => $insert_data['device_id'],
//                    'room_device_id'        => $params['id'],
//                    'coefficient'           => $insert_data['coefficient'],
//                    'price'                 => $insert_data['price'],
//                    'base_number'           => $insert_data['base_number'],
//                    'reading'               => $insert_data['reading'],
//                    'use_total'             => $insert_data['use_total'],
//                    'lift_fee'              => $insert_data['lift_fee'],
//                    'second_pressure_fee'   => $insert_data['second_pressure_fee'],
//                    'total_fee'             => $insert_data['total_fee'],
//                    'log_time'              => $insert_data['log_time'],
//                ];
//                RoomDepartmentDeviceLog::create($log_data);
//            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function editField(array $params): bool {
        $info = RoomDepartmentDevice::find($params['id']);
        Db::startTrans();
        try {
            $field = "{$params['field']}";
            RoomDepartmentDevice::where('id', $params['id'])->update(["{$field}" => $params['value']]);
            //未初始化
            if ($info['is_init'] == InitEnum::NO) {
                //获取最新的
                $last_log = RoomDepartmentDeviceLog::where('device_id', $params['id'])->order('create_time', 'desc')->find();
                if (isset($last_log["{$field}"])) {
                    RoomDepartmentDeviceLog::where('id', $last_log['id'])->update(["{$field}" => $params['value']]);
                }
            } else {
                self::setError('已初始化无法再列表直接编辑');
                return false;
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function setSave(array $params): bool {
        Db::startTrans();
        $params['total_fee'] = ($params['reading'] - $params['base_number']) * $params['coefficient'] * $params['price'];

        if (!empty($params['reading']) && !empty($params['base_number'])) {
            $params['use_total'] = $params['reading'] - $params['base_number'];
        }
        if (
            !empty($params['coefficient'])
            && !empty($params['price'])
            && !empty($params['base_number'])
            && !empty($params['reading'])
            && !empty($params['lift_fee'])
            && !empty($params['second_pressure_fee'])
        ) {
            $params['total_fee'] = (($params['reading'] - $params['base_number']) * $params['coefficient'] * $params['price']) + $params['lift_fee'] + $params['second_pressure_fee'];
        }

        try {
            $save_data = [
                'update_time' => date("Y-m-d H:i:s"),
                'coefficient' => $params['coefficient'],
                'price' => $params['price'],
                'base_number' => $params['base_number'],
                'reading' => $params['reading'],
                'use_total' => $params['use_total'],
                'total_fee' => round($params['total_fee'], 2),
                'lift_fee' => $params['lift_fee'],
                'second_pressure_fee' => $params['second_pressure_fee'],
            ];
            if ($params['reading'] && $params['reading'] * 1 > 0) {
                $save_data['log_time'] = date("Y-m-d H:i:s");
            }
            RoomDepartmentDevice::where('id', $params['id'])->update($save_data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/23 10:30
     */
    public static function delete(array $params): bool {
        $id = $params['id'];
        if (!is_array($id)) {
            $id = [$id];
        }
        $ids = RoomDepartmentDevice::where([
            ["room_master", "=", "0"],
            ["id", "in", $id],
        ])->column("id");
        return RoomDepartmentDevice::destroy($ids);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/02/23 10:30
     */
    public static function detail($params): array {
        return RoomDepartmentDevice::findOrEmpty($params['id'])->toArray();
    }

    public static function updateStatus(array $params) {
        RoomDepartmentDevice::update([
            'id' => $params['id'],
            'status' => $params['status']
        ]);
        return true;
    }


    public static function updateInit(array $params) {
        $ym = date("Ym");
        $this_time = date("Y-m-d H:i:s");
        $db = new \think\Db();


        // 设备数据统计并记录
        $device_log_save = RoomDepartmentDevice::alias('a')->field([
            "{$ym} as log_date", "'{$this_time}' as add_time", "'{$this_time}' as update_time", "'{$this_time}' as log_time",
            "a.cid", "a.bid", "a.rid", "a.log_time",
            "a.device_id", "a.device_name", "a.device_no", "a.device_type",
            "a.base_number", "IF(a.reading is null, a.base_number, a.reading) as reading",
            "a.coefficient", "a.price", "a.use_total", "a.total_fee",
        ])->where([
            ["a.status", "=", 1],
        ])->append([
            "no_append",
        ])->select()->toArray();
        (new RoomDepartmentDeviceLog())->saveAll($device_log_save);
//        var_dump($device_log_save);exit;


        $room_stat = RoomDepartment::field([
            "*", "id as rid",
            "{$ym} as log_date", "'{$this_time}' as add_time", "'{$this_time}' as update_time", "'{$this_time}' as log_time",
        ])->where([
            ["status", "=", "1"]
        ])->with([
            "campus", "building", // "allDevice",
        ])->withSum(["allDevice" => function ($query, &$alias) {
            $alias = 'room_s_use_total';
            $query->where('device_type', 1);
        }], "use_total")->withSum(["allDevice" => function ($query, &$alias) {
            $alias = 'room_s_price';
            $query->where('device_type', 1);
        }], "price")->withSum(["allDevice" => function ($query, &$alias) {
            $alias = 'room_s_total_fee';
            $query->where('device_type', 1);
        }], "total_fee")->withSum(["allDevice" => function ($query, &$alias) {
            $alias = 'room_d_use_total';
            $query->where('device_type', 2);
        }], "use_total")->withSum(["allDevice" => function ($query, &$alias) {
            $alias = 'room_d_price';
            $query->where('device_type', 2);
        }], "price")->withSum(["allDevice" => function ($query, &$alias) {
            $alias = 'room_d_total_fee';
            $query->where('device_type', 2);
        }], "total_fee")->withSum(["allDevice" => function ($query, &$alias) {
            $alias = 'room_all_total_fee';
        }], "total_fee")->append([
            "no_append",
        ])->select()->each(function (&$item) {
            unset($item['id']);
            return $item;
        })->toArray();
        foreach ($room_stat as &$item) {
            $item['cname'] = $item['campus']['name'] ?? '';
            $item['bname'] = $item['building']['name'] ?? '';

            $item['room_s_use_total'] = $item['room_s_use_total'] * 1;
            $item['room_s_price'] = $item['room_s_price'] * 1;
            $item['room_s_total_fee'] = $item['room_s_total_fee'] * 1;
            $item['room_d_use_total'] = $item['room_d_use_total'] * 1;
            $item['room_d_price'] = $item['room_d_price'] * 1;
            $item['room_d_total_fee'] = $item['room_d_total_fee'] * 1;
            $item['room_all_total_fee'] = $item['room_all_total_fee'] * 1;

//            $item['room_all_total_fee'] = 1 * sprintf("%.6f", array_sum([
//                    $item['room_all_total_fee'], $item['lift_fee'], $item['second_pressure_fee'],
//                ]));
//            $item['lift_fee'] = $item['lift_fee'] * 1;
//            $item['second_pressure_fee'] = $item['second_pressure_fee'] * 1;
        }
        (new RoomDepartmentLog())->saveAll($room_stat);
//        var_dump($room_stat);exit;


        // 设备数据清空
        RoomDepartmentDevice::where([
            ["status", "=", 1],
        ])->update([
            "base_number" => $db->raw("reading"),
            "use_total" => 0, // 使用量
            "total_fee" => 0, // 总费用
            "log_time" => null,
            "update_time" => date("Y-m-d H:i:s"),
            "lift_fee" => 0, // 电梯费
            "second_pressure_fee" => 0, // 二次压力费
        ]);


        // 房间数据清空
        RoomDepartment::where([
            ["status", "=", 1],
        ])->update([
            "device_total" => 0,
            "update_time" => date("Y-m-d H:i:s"),
        ]);


        return true;
    }


}


